<style scoped>

</style>
<template>
  <van-tabs class="box-tab-list" v-model:active="activeIndex" swipeable>
    <van-tab v-for="(title,i) in thisData.title_list" :title="title" :name="i">
      <PageBlock v-if="_children_ && _children_[i]" v-bind="_children_[i]" :info="_info_"></PageBlock>
    </van-tab>
  </van-tabs>
</template>

<script>

import PageBlock from "@/components/auto_import/PageBlock.vue";
import {cache} from "@/js/s94_tool.js";

export default {
  _title_: '标签页',
  _tip_: '每一个标签对应一个子组件，子组件的$info继承当前组件的$info',
  _head_img_: '',
  _group_: '容器组件',
  components: {PageBlock},
  props:{
    title_list: {
      type: [String, Array],
      default: '标签一,标签二',
      _label_: '标题',
      _tip_: '每个标签页的标题，多个逗号分隔',
      _required_: true,
      _default_: '标签一,标签二',
    },
    index: {
      type: [String, Number],
      _label_: '默认显示',
      _tip_: '默认显示的标签序列号，0~标签数量-1',
    },

    _info_: [String, Object, Array],
    _children_: Array,
  },
  data(){
    return {
      activeIndex: 0,
    }
  },
  methods:{
    cacheActiveIndex(){
      // 窗口关闭（刷新）的时候，缓存2秒 activeIndex ，用于刷新后，优先定位到当前 activeIndex 同时不影响路由跳转等其他情况
      cache({[this.cacheKey]: this.activeIndex+''}, 2);
    }
  },
  computed:{
    cacheKey(){
      let title_list = typeof this.title_list === 'string' ? this.title_list : this.title_list.join(',')
      return 'BoxTabList.activeIndex:'+title_list;
    },
    thisData(){
      let title_list = this.title_list;
      if (title_list && typeof title_list === 'string') title_list = title_list.split(',');
      if (!Array.isArray(title_list)) title_list = [];
      return{
        title_list,
      }
    }
  },
  mounted(){
    let activeIndex = cache(this.cacheKey);
    if (isNaN(activeIndex)){
      activeIndex = this.index;
    }
    if (!isNaN(activeIndex) && activeIndex>=0 && activeIndex<=this.thisData.title_list.length-1){
      this.activeIndex = parseInt(activeIndex);
    }

    window.addEventListener('beforeunload', this.cacheActiveIndex)
  },
  unmounted() {
    window.removeEventListener('beforeunload', this.cacheActiveIndex)
  }
}
</script>